(function () {
	
     ////提交人
	
	//获取显示页面数据 服务器分页
    var sectionData = {};
    var sectionTable;
    jQuery(document).ready(function () {
    	sectionTable = jQuery('#sectionTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/section/getpage',
                "data": function (d) {
                    return $.extend({}, d, sectionData);
                }
            },
            columns: [
                {
                	data: null
                },
                {
    	            data: null,
    	            defaultContent: "",
    	            render: function (data, type, full, meta) {
    	            	var id=data.id
    	            	var operate ='<input type="checkbox" class="checkchild">';
    	            	return operate;
    	            }   
                },
                {
                    data: 'sectionName'
                },
                {
                    data: 'chief.empLogin.userName'
                },
                {
                    data: 'superior'
                }
                ],
            "drawCallback": function (oSettings) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                    k++;
                }
            }
        });
    });	
    	///新增
    	jQuery('.addBtn').on("click", function() {
    		jQuery('#id').val('');
    		jQuery('#sectionName').val('');
    		jQuery('#superior').val('');
    		jQuery("#chief").select2().val('').trigger("change");
    		jQuery('#sectionModal').modal('show');
    	});
    	// 保存按钮
    	jQuery('.saveBtn').on('click', function() {
    		if (jQuery("#sectionForm") && !jQuery("#sectionForm").Validform({
    			tiptype : 3,
    			showAllError : true
    		}).check(false)) {
    			return;
    		};
    		var isId = jQuery("#id").val();
    		var sectionName = jQuery('#sectionName').val();
    		var superior = jQuery('#superior').val();
    		var chiefid=jQuery("#chief").val();
    		var sectionArea=superior+'-'+sectionName;
    		//验证唯一性
    		var d={
    				"id":isId,
    				"sectionArea":sectionArea
    		}
    		var url=window.rootPath+"/ui/section/namevalidate";
    		jQuery.ajax({
    			url:  encodeURI(url),
    			cache:false,
    			data:d,
                type: 'get',
                dataType: 'json',
    			success:function(data){
    				if(data.code>0){
                		message(superior+"已存在"+sectionName)
    				}else{
    					// 判断是编辑还是新增
    					if (isId == "") {
    						var api = window.rootPath + "/ui/section/saveSection";
    						var d = {
    							"sectionName" : sectionName,
    							"superior" : superior,
    							"sectionArea" : sectionArea,
    							"chief":{
    								"id":chiefid
    							}
    						};
    						jQuery.ajax({
    							type : 'post',
    							url : api,
    							data : JSON.stringify(d),
    							dataType : 'json',
    							contentType : 'application/json;charset=utf-8',
    							success : function(data) {
    								jQuery('#sectionModal').modal('hide');
    								sectionTable.draw();
    							}
    						});
    					} else {
    						var data = {
    							"id" :isId,
    							"sectionName" : sectionName,
    							"superior" : superior,
    							"sectionArea" : sectionArea,
    							"chief":{
    								"id":chiefid
    							}
    						};
    						var url = window.rootPath +"/ui/section" ;
    						jQuery.ajax({
    							url : encodeURI(url),
    							type : 'patch',
    							data : JSON.stringify(data),
    							dataType : 'json',
    							contentType : 'application/json;charset=utf-8',
    							success : function() {
    								jQuery('#sectionModal').modal('hide');
    								sectionTable.draw(false);
    							}
    						});
    					}
    				}
    			}
    		});

    	});
    	// 编辑按钮
    	jQuery('.editBtn').on('click', function() {
    		var selects=getSelect("#sectionTable",1);
    	  	   if(selects.length>1){
    	  		   $.springLemonDialog({
    	  		         content: '只能操作一条记录',// 确认文本
    	  		         clickButton: function (sender, modal, index) {// 按钮事件处理
    	  		             $(this).closeDialog(modal);
    	  		         }
    	  		   }); 
    	  	   }
    	  	   else if(selects.length==0){
    	  		   $.springLemonDialog({
    	  		         content: '请选择要操作的记录',// 确认文本
    	  		         clickButton: function (sender, modal, index) {// 按钮事件处理
    	  		             $(this).closeDialog(modal);
    	  		         }
    	  		   }); 
    	  	   }else if(selects.length==1){
    	  		    var id=selects[0].id;
	    			jQuery('#id').val(id);
	    			jQuery('#sectionName').val(selects[0].sectionName);
	    			jQuery('#superior').val(selects[0].superior);
	    			jQuery("#chief").select2().val(selects[0].chief.id).trigger("change");
	    			jQuery('#sectionModal').modal('show');  
    	  	   }
    	});
    	// 删除按钮
    	jQuery('.deleteBtn').on('click', function() {
    		var selects=getSelect("#sectionTable",1);
        	var url = window.rootPath + "/ui/section/deleteSection";
     	    delSelect(selects,url,sectionTable) 
    	});
    	
    	//查询
        jQuery('.searchBtn').on('click',function(){
        	sectionData.key=jQuery('#keyword').val();
        	sectionTable.draw();
        })
        //撤销查询
        jQuery('.resetBtn').on("click",function()
        {
            jQuery('#keyword').val('');
            sectionData.key ='';
            sectionTable.draw();
        });
        
        //列表中的全选
        $("#checkAll").click(function(){
        	var check = $(this).prop("checked");
            $(".checkchild").prop("checked", check);
    	});
        
        ///配置片区
        jQuery('.areaBtn').click(function(){
        	var selects=getSelect("#sectionTable",1);
 	  	   if(selects.length>1){
 	  		   message("只能操作一条记录");
 	  	   }
 	  	   else if(selects.length==0){
 	  		   message("选择操作的一条记录");
 	  	   }else if(selects.length==1){
 	  		    var id=selects[0].id;
 	  		    var superior=selects[0].superior;
 	  		      jQuery('#sectionshow').text(selects[0].sectionArea);
	    			jQuery('#sectionId').val(id);
	    			jQuery('#superior').val(superior);
	    			noSelectData.sectionId=id;
	    			noSelectData.superior=superior;
	    			noSelectTable.draw();
	    			selectData.sectionId=id;
	    			selectTable.draw();
	    			jQuery('#areaModal').modal('show');    
 	  	   }	
        });
        
 ////////////////////获得没被添加的片区//////////////////////////////////////////////////
        var noSelectData = {};
        noSelectData.sectionId="";
        noSelectData.superior=""
        var noSelectTable;
        jQuery(document).ready(function () {
        	noSelectTable = jQuery('#noSelectTable').DataTable({
                "serverSide": true,
                "iDisplayLength": 5,
                "ordering": false,
                "ajax": {
                    "dataType": "json",
                    "type": "get",
                    "cache": false,
                    "url":window.rootPath+ '/ui/section/getnoselectpage',
                    "data": function (d) {
                        return $.extend({}, d, noSelectData);
                    }
                },
                
                columns: [
                    {
                    	data: null
                    },
                    {
	                    data: null,
	                    defaultContent: "",
	                    render: function (data, type, full, meta) {
	                        var operate ='<button type="button" class="btn btn-sm btn-info addAreaBtn">配置</button>';
	                        return operate;

	                    }
	                },
                    {
                        data: 'areaCode'
                    },
                    {
                        data: 'superiorArea'
                    }
                    ],
                "drawCallback": function (oSettings) {
                    var k = 0;
                    var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                    for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                        $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                        k++;
                    }
                    noSelectTable.off('click', 'tr');
                    noSelectTable.on('click', 'tr', function (event) {
	                    event = event || window.event;
	                    var target = event.target || event.scrElement;
	                    var data = noSelectTable.row(this).data();
	                    if (target.className.indexOf('fa-remove') != -1 || target.className.indexOf('addAreaBtn') != -1) {
	                    	addArea(data);
	                    }
	                    return;
	                });
                }
            });
        });
        function addArea(data){
        	if (!data) return;
        	var url = window.rootPath + '/ui/section/addArea';
        	var sectionId=jQuery('#sectionId').val();
        	var saleAreaId=data.id
        	var d = {
    				"section" : {
    					"id" : sectionId
    				},
    				"saleArea" : {
    					"id" : saleAreaId
    				}
    			}
        	jQuery.ajax({
				url : encodeURI(url),
				type : 'post',
				data : JSON.stringify(d),
				dataType : 'json',
				contentType : 'application/json;charset=utf-8',
				success : function(data) {	
	    			noSelectData.sectionId=jQuery('#sectionId').val();
	    			noSelectData.superior=jQuery('#superior').val();
	    			noSelectTable.draw();
	    			selectData.sectionId=jQuery('#sectionId').val();;
	    			selectTable.draw();
				}
			});	
        }
        
 ////////获得被配置的片区////////////////////////////
        var selectData = {};
        selectData.sectionId="";
        var selectTable;
        jQuery(document).ready(function () {
        	selectTable = jQuery('#selectTable').DataTable({
                "serverSide": true,
                "iDisplayLength": 5,
                "ordering": false,
                "ajax": {
                    "dataType": "json",
                    "type": "get",
                    "cache": false,
                    "url":window.rootPath+ '/ui/section/getselectpage',
                    "data": function (d) {
                        return $.extend({}, d, selectData);
                    }
                },
                
                columns: [
                    {
                    	data: null
                    },
                    {
	                    data: null,
	                    defaultContent: "",
	                    render: function (data, type, full, meta) {
	                        var operate ='<button type="button" class="btn btn-sm btn-info delAreaBtn">取消配置</button>';
	                        return operate;

	                    }
	                },
                    {
                        data: 'saleArea.areaCode'
                    },
                    {
                        data: 'saleArea.superiorArea'
                    }
                    ],
                "drawCallback": function (oSettings) {
                    var k = 0;
                    var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
                    for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                        $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                        k++;
                    }
                    selectTable.off('click', 'tr');
                    selectTable.on('click', 'tr', function (event) {
	                    event = event || window.event;
	                    var target = event.target || event.scrElement;
	                    var data = selectTable.row(this).data();
	                    if (target.className.indexOf('fa-remove') != -1 || target.className.indexOf('delAreaBtn') != -1) {
	                    	delArea(data);
	                    }
	                    return;
	                });
                }
            });
        });  
        function delArea(data){
        	if (!data) return;
        	var url =window.rootPath+ "/api/sectionAreas/" + data.id;
        	var taskId=data.id;
            jQuery.ajax({
                url: encodeURI(url),
                cache: false,
                type: "delete",
                dataType: "json",
                success: function (data) {
                	noSelectData.sectionId=jQuery('#sectionId').val();
	    			noSelectData.superior=jQuery('#superior').val();
	    			noSelectTable.draw();
	    			selectData.sectionId=jQuery('#sectionId').val();;
	    			selectTable.draw();
                }
            });
        	
        }
        
        

})();